{% from "macros.jinja" import hiding_control %}
{% extends "base_logged.html" %}

{% macro render_field(field, label_visible=true) -%}
     <div class="form-group {% if field.errors %}has-error{% endif %} {{ kwargs.pop('class_', '') }}" id="form-group-{{ field.name }}">
        {% if field.type != 'HiddenField' and label_visible %}
            {{ field.label(class_='col-sm-2 control-label') }}
        {% endif %}
        <div class="col-sm-10 input-group">
          {{ field(class_='form-control', **kwargs) }}
          {% if field.errors %}
              {% for e in field.errors %}
                  <span class="help-block">{{ e }}</span>
              {% endfor %}
          {% endif %}
        </div>
    </div>
{%- endmacro %}


{% block page %}
<div id="page-wrapper">

<div class="row">
  <div class="col-lg-12">
    <h1>Execute module on minions</h1>
    <ol class="breadcrumb">
      <li><a href="{{ url_for('index') }}"><i class="fa fa-dashboard"></i> SaltPad</a></li>
      <li class="active"><i class="fa fa-terminal"></i> Run module</li>
    </ol>
  </div>
</div><!-- /.row -->

  <div class="row">
    <div class="col-lg-12">
      <form method="POST" class="form-horizontal" role="form" action="{{ url_for('run') }}" id="run_form">
        {{ form.csrf_token }}
        {{ render_field(form.expr_form) }}
        {{ render_field(form.tgt) }}
        {{ render_field(form.fun) }}

        <div class="panel panel-default" id="optional_panel" style="display: none">
          <div class="panel-heading">
            <h3 class="panel-title">{{hiding_control('hide_control', True)|safe }} Optional arguments</h3>
          </div>
          <div class="panel-body" id="optional_arguments" style="display: none">
          </div>
        </div>

        <div class="form-group" id="submit">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default">Run cmd</button>
          </div>
        </div>
      </form>
    </div>
    <div class="col-lg-12">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Functions docs</h3>
        </div>
        <div class="panel-body">
          <pre id="doc-placeholder"></pre>
        </div>
      </div>
    </div>
  </div><!-- /.row -->

{% endblock %}

{% block scripts %}
<script type="text/javascript">

function template(field_name, default_value, required) {
  return '<div class="form-group run-arg" id="form-group-fun">' +
  '<label class="col-sm-2 control-label" for="' + field_name + '">' + field_name + '</label><div class="col-sm-10 input-group">' +
  (required ? '<div class="input-group-addon">*</div>' : '') +
  '<input class="form-control" id="' + field_name + '" name="' + field_name + '" type="text" ' +
  (default_value ? 'placeholder="' + default_value + '" ' : '') +
  (required ? 'required="required" ' : '') +
  '></div></div>';
}

function append_input_field_before(field_id, field_name, default_value, required) {
  $(field_id).before(template(field_name, default_value, required));
}

function insert_input_field(field_id, field_name, default_value, required) {
  $(field_id).append(template(field_name, default_value, required));
}


$(function() {
  var timer;
  var delay = 300; // 0.3 seconds delay after last input

  $("div.panel-heading i.hide_control").click(function(event) {
    $(this).parents("div.panel").first().find("div.panel-body").toggle();
    $(this).parent().find("i.fa").toggle();
  });


  $('#fun').on('input', function() {
    window.clearTimeout(timer);
    timer = window.setTimeout(function(){

      // Clear old inputs
      $("#run_form").find('.run-arg').remove();
      // Hide optional panel and arguments
      $("#optional_panel").hide();
      $("#optional_arguments").hide();
      // Hiding control reset
      $(".control_on_hidden").show();
      $(".control_on_showed").hide();
      // Clear docs
      $("#doc-placeholder").text('');

      var exact_fun = $('#fun').val()

      var data = {
        'expr_form': $('#expr_form').val(),
        'tgt': $('#tgt').val(),
        'fun': exact_fun
      };
      $.ajax({
        url: "{{ url_for('doc_search') }}",
        type: "post",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function (data, status) {

          // Update doc and update form
          if(data instanceof String || typeof data == 'string') {
             $("#doc-placeholder").text("Invalid docs: " + data);
             return
          }


          // New doc content
          var new_text = '';

          // Iterate on data
          for (var function_name in data) {
            function_doc = data[function_name].doc;
            new_text += function_name + function_doc + '\n';

            // Only show forms if it's the right function
            if (function_name == exact_fun) {
              // Required args
              data[function_name].spec.required_args.map(function(e) {
                append_input_field_before("#optional_panel", e, "Enter input", true);
              });

              // Optionnal args
              default_args = data[function_name].spec.default_args;
              if(default_args == undefined){
                $("#optional_panel").hide();
              } else {
                $("#optional_panel").show();
                $.map(default_args, function(value, key) {
                  insert_input_field("#optional_arguments", key, value);
                });
              }
            }
          }

          // Set new doc pre
          $("#doc-placeholder").text(new_text);
        },
        error: function (err) {
          $("#doc-placeholder").text(err.responseText);
        }
      });
    }, delay);
  })
});
</script>
{% endblock %}
